//
//  LoginKJViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/8/19.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "LoginKJViewController.h"

#import "RigisterViewController.h"
#import "TabbarViewController.h"
#import "AppDelegate.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import "WXApi.h"


#define WXDoctor_App_ID @"wx30c359eef38260d1" // 注册微信时的AppID
#define WXDoctor_App_Secret @"2f728600846ac30db053e2254fd01f04" // 注册时得到的AppSecret
#define WXPatient_App_ID @"wx30c359eef38260d1"
#define WXPatient_App_Secret @"2f728600846ac30db053e2254fd01f04"
#define WX_ACCESS_TOKEN @"access_token"
#define WX_OPEN_ID @"openid"
#define WX_REFRESH_TOKEN @"refresh_token"
#define WX_UNION_ID @"unionid"
#define WX_BASE_URL @"https://api.weixin.qq.com/sns"

@interface LoginKJViewController ()<TencentSessionDelegate,WXApiDelegate>
{
    NSInteger count;
    TencentOAuth *tencentOAuth;
    NSArray *permissions;
    AppDelegate *appdelegate;

}
@property (weak, nonatomic) IBOutlet UITextField *textNum;
@property (weak, nonatomic) IBOutlet UITextField *textCode;
@property (weak, nonatomic) IBOutlet UIView *view1;
@property (weak, nonatomic) IBOutlet UIView *view2;
@property (weak, nonatomic) IBOutlet UIButton *btnCode;

@property (copy, nonatomic) void (^requestForUserInfoBlock)();

@end

@implementation LoginKJViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _view1.layer.borderWidth = 1.0;
    _view1.layer.borderColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0].CGColor;
    
    _view2.layer.borderWidth = 1.0;
    _view2.layer.borderColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0].CGColor;
    
    [self loadNav];

    
}


- (void)loadNav{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    view.backgroundColor = [UIColor whiteColor];
    view.userInteractionEnabled = YES;
    [self.view addSubview:view];
    
    UILabel *line = [[UILabel alloc] init];
    line.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:line];
    [line makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(0);
        make.right.equalTo(0);
        make.bottom.equalTo(view.bottom);
        make.height.equalTo(0.5);
    }];
    
    UILabel *lab = [[UILabel alloc] init];
    lab.text = @"快捷登录";
    lab.textColor = [UIColor blackColor];
    lab.font = [UIFont systemFontOfSize:18.0];
    [view addSubview:lab];
    [lab makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view.centerX);
        make.top.equalTo(34);
    }];
    
    //返回按钮
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateHighlighted];
    [btn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    [btn makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(lab.centerY);
        make.left.equalTo(10);
        make.width.equalTo(30);
        make.height.equalTo(30);
    }];
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn2 setTitle:@"注册" forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(loadZhuCe) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn2];
    [btn2 makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(lab.centerY);
        make.right.equalTo(-10);
        make.width.equalTo(40);
        make.height.equalTo(30);
    }];
}

- (void)clickBack{
//    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)loadZhuCe{
    RigisterViewController *rigister = [[RigisterViewController alloc] init];
    [self.navigationController pushViewController:rigister animated:YES];
}
//获取验证码
- (IBAction)btnCode:(id)sender {
    if (_textNum.text.length == 0) {
        
        [LICGToast showWithText:@"手机号不能为空"];
    }else if ([self validateMobile:_textNum.text] == 0){
        [LICGToast showWithText:@"手机号格式不正确"];
    }else{
        [self performSelector:@selector(countClick) withObject:nil];
        _btnCode.enabled = NO;
        
        NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
        [parmas setObject:_textNum.text forKey:@"mobile"];
        [parmas setObject:@"3" forKey:@"k"];
        NSLog(@"parmas:%@",parmas);
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSString *url = [NSString stringWithFormat:@"%@/App/Userlogin/CallSms",urlHead];
        [manager POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
            NSLog(@"res:%@",responseObject);
            NSString *str = [responseObject objectForKey:@"status"];
            if ([str integerValue] == 200) {
                
                [LICGToast showWithText:@"消息发送成功"];
            }else{
                [LICGToast showWithText:[responseObject objectForKey:@"msg"]];
            }
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"error:%@",error);
        }];
        
    }
    
}

-(void)countClick
{
    
    count = 119;
    [_btnCode setTitle:@"119秒后重新获取" forState:UIControlStateNormal];
    
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
}

- (void)timerFired:(NSTimer *)time{
    if (count !=1) {
        count -=1;
        
        NSString *str = [NSString stringWithFormat:@"%li",count];
        NSString *str2 = @"秒后重新获取";
        NSString *title = [NSString stringWithFormat:@"%@%@",str,str2];
        
        [_btnCode setTitle:title forState:UIControlStateNormal];
    }else{
        [time invalidate];//关闭定时器
        _btnCode.enabled = YES;
        [_btnCode setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
    
}
//短信登录
- (IBAction)btnLogin:(id)sender {
    
    if ([self validateMobile:_textNum.text] == 0) {
        [LICGToast showWithText:@"电话号不能为空"];
        return;
    }else if([self validateMobile:_textNum.text] == 0){
        [LICGToast showWithText:@"电话号码格式不正确"];
        return;
    }else if (_textCode.text.length == 0){
        [LICGToast showWithText:@"验证码不能为空"];
        
        return;
    }
    
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:[NSString stringWithFormat:@"%li",[_textNum.text integerValue]] forKey:@"mobilephone"];
    [parmas setObject:[NSString stringWithFormat:@"%li",[_textCode.text integerValue]] forKey:@"smscode"];
    [parmas setObject:@"2" forKey:@"type"];
    [parmas setObject:[user objectForKey:@"token"] forKey:@"pushtoken"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = [NSString stringWithFormat:@"%@/App/Userlogin/quickLogin",urlHead];
    [manager POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"短信登录res:%@",responseObject);
        NSString *state = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"status"] integerValue]];
        if ([state integerValue] == 200) {
            NSString *userid = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"userid"] integerValue]];
            NSString *token = [responseObject objectForKey:@"token"];
            [user setObject:userid forKey:@"userid"];
            [user setObject:token forKey:@"token2"];
            
            [self.delegate send:@"suc"];
            [self.navigationController popViewControllerAnimated:YES];
            
            [LICGToast showWithText:@"登录成功"];
        }else{
            [LICGToast showWithText:[responseObject objectForKey:@"msg"]];
            
        }
        
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        
        [SVProgressHUD dismiss];
    }];
    
}
//返回密码登录
- (IBAction)clickBackLogin:(id)sender {
    //[self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}
//
- (IBAction)clickWeiXin:(id)sender {
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:WX_ACCESS_TOKEN];
    NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:WX_OPEN_ID];
    if (accessToken && openID) {
        NSString *refreshToken = [[NSUserDefaults standardUserDefaults] objectForKey:WX_REFRESH_TOKEN];
        NSString *refreshUrlStr = [NSString stringWithFormat:@"%@/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@", WX_BASE_URL, WXPatient_App_ID, refreshToken];
           AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:refreshUrlStr parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            NSDictionary *refreshDict = [NSDictionary dictionaryWithDictionary:responseObject];
            NSString *reAccessToken = [refreshDict objectForKey:WX_ACCESS_TOKEN];
            // 如果reAccessToken为空,说明reAccessToken也过期了,反之则没有过期
            if (reAccessToken) {
                // 更新access_token、refresh_token、open_id
                [[NSUserDefaults standardUserDefaults] setObject:reAccessToken forKey:WX_ACCESS_TOKEN];
                [[NSUserDefaults standardUserDefaults] setObject:[refreshDict objectForKey:WX_OPEN_ID] forKey:WX_OPEN_ID];
                [[NSUserDefaults standardUserDefaults] setObject:[refreshDict objectForKey:WX_REFRESH_TOKEN] forKey:WX_REFRESH_TOKEN];
                [[NSUserDefaults standardUserDefaults] synchronize];
                // 当存在reAccessToken不为空时直接执行AppDelegate中的wechatLoginByRequestForUserInfo方法
                !self.requestForUserInfoBlock ? : self.requestForUserInfoBlock();
                
                [self wxLogin];
                
            }
            else {
                [self wechatLogin];
            }
            
            [SVProgressHUD dismiss];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"error:%@",error);
            
            [SVProgressHUD dismiss];
        }];
    }
}

-(void)wxLogin
{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:@"wechat" forKey:@"threetype"];
    [parmas setObject:[user objectForKey:@"openid"] forKey:@"openid"];
    [parmas setObject:@"2" forKey:@"type"];
    [parmas setObject:[user objectForKey:@"token"] forKey:@"pushtoken"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = [NSString stringWithFormat:@"%@/App/Userlogin/threepartylogin",urlHead];
    [manager POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"短信登录res:%@",responseObject);
        NSString *state = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"status"] integerValue]];
        if ([state integerValue] == 200) {
            NSString *userid = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"userid"] integerValue]];
            NSString *token = [responseObject objectForKey:@"token"];
            [user setObject:userid forKey:@"userid"];
            [user setObject:token forKey:@"token2"];
            NSString *phoneState =[NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"phoneState"] integerValue]];
            if ([phoneState isEqualToString:@"3"]) {//  未绑定
                //去绑定手机号
                
            }
            [self.delegate send:@"suc"];
            [self.navigationController popViewControllerAnimated:YES];
            
            [LICGToast showWithText:@"登录成功"];
        }else{
            [LICGToast showWithText:[responseObject objectForKey:@"msg"]];
            
        }
        
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        
        [SVProgressHUD dismiss];
    }];
}
- (void)wechatLogin {
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = @"iosApp";
        [WXApi sendReq:req];
    }
    else {
        [self setupAlertController];
    }
}
#pragma mark - 设置弹出提示语
- (void)setupAlertController {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先安装微信客户端" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:actionConfirm];
    [self presentViewController:alert animated:YES completion:nil];
}

//
- (IBAction)clickQQ:(id)sender {
    tencentOAuth=[[TencentOAuth alloc]initWithAppId:@"1106426854" andDelegate:self];
    tencentOAuth.authShareType= AuthShareType_QQ;
    permissions= [NSArray arrayWithObjects:@"get_user_info",@"get_simple_userinfo",@"add_t",nil];
    [tencentOAuth authorize:permissions];
}
//
- (IBAction)clickZFB:(id)sender {
    
}


//登陆完成调用
- (void)tencentDidLogin
{
    if (tencentOAuth.accessToken && 0 != [tencentOAuth.accessToken length])
    {
         [user setObject:tencentOAuth.openId forKey:@"openid"];// 获取qq openid
        //  记录登录用户的OpenID、Token以及过期时
        [tencentOAuth getUserInfo];
    }
    else
    {
      //  tokenLable.text = @"登录不成功 没有获取accesstoken";
    }
}

// 网络错误导致登录失败：
-(void)tencentDidNotNetWork
{
    NSLog(@"tencentDidNotNetWork");
}
//非网络错误导致登录失败：
-(void)tencentDidNotLogin:(BOOL)cancelled
{
    NSLog(@"tencentDidNotLogin");
    if (cancelled)
    {

    }else{
       
    }
}
#pragma mark -- qq获取用户个人信息
- (void)getUserInfoResponse:(APIResponse*)response
{
    NSLog(@"response -- %@", response.jsonResponse);
   
    [user setObject:response.jsonResponse[@"nikename"] forKey:@"nikename"];//nikename
    [self qqLogin];

}

- (void)qqLogin
{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:@"QQ" forKey:@"threetype"];
    [parmas setObject:[user objectForKey:@"openid"] forKey:@"openid"];
    [parmas setObject:@"2" forKey:@"type"];
//    [parmas setObject:[user objectForKey:@"token"] forKey:@"pushtoken"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = [NSString stringWithFormat:@"%@/App/Userlogin/threepartylogin",urlHead];
    [manager POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
       
        NSString *state = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"status"] integerValue]];
        if ([state integerValue] == 200)
        {
            NSString *userid = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"userid"] integerValue]];
            NSString *token = [responseObject objectForKey:@"token"];
            [user setObject:userid forKey:@"userid"];
            [user setObject:token forKey:@"token2"];
            NSString *phoneState =[NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"phoneState"] integerValue]];
            if ([phoneState isEqualToString:@"3"]) {//  未绑定
                //去绑定手机号
                
            }
            
            [self.delegate send:@"suc"];
            [self.navigationController popViewControllerAnimated:YES];
            
            [LICGToast showWithText:@"登录成功"];
        }else{
            [LICGToast showWithText:[responseObject objectForKey:@"msg"]];
            
        }
        
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        
        [SVProgressHUD dismiss];
    }];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
